var api = require('./../../config/api.js');
var app = getApp();
var util = require('./../../utils/util.js');

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		schoolList: [],
		schoolIdList: [],
		schoolText: '请选择',
		lockSchool: false,
		schoolId: 0,
		name: "",
		man: true, // 是否为男性
		effectiveMobile: '', // 有效的电话号码
		mobile: "", // 手机号
		next: "back",
		isReadMbile: false,
		isHaveMobile: false,
		btnCodeText: '获取验证码',
		authCode: '',
		isShowAuthCode: false,
		isFirst: false,
		isAgree: true,
		isAuth: true, // 默认要授权
		redirectTo: '/pages/home/index'
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		if (!app.globalData.userInfo.uName) {
      wx.redirectTo({
        url: '../login/login'
      })
      return
    }
		if (app.globalData.userInfo.uName != null) { // 已授权
			this.setData({isAuth: !this.data.isAuth})
		}
		console.log(app.globalData.userInfo)
		if (options.next) {
			this.setData({
				next: options.next
			});
		}
		var that = this;

		util.myRequest(api.SchoolList, false, function(data) {

			that.setData({
				schoolList: data.data.nameList,
				schoolIdList: data.data.idList,
			})

			// 加载默认信息
			if (app.globalData.userInfo.addition) {
				that.setData({
					schoolText: app.globalData.userInfo.addition.uSchool,
					schoolId: app.globalData.userInfo.addition.uCustomInfo.csId,
					name: app.globalData.userInfo.addition.uName,
					man: app.globalData.userInfo.addition.uSex,
					mobile: app.globalData.userInfo.addition.uMobile,
					isHaveMobile: true,
				});
				if (app.globalData.userInfo.addition.uCustomInfo.csId != 0) {
					that.setData({
						lockSchool: false
					});
				}
				// 判断是否拥有有效的手机号
				if (app.globalData.userInfo.addition.uMobile) {
					that.setData({
						effectiveMobile: app.globalData.userInfo.addition.uMobile
					});
				}
			}
		});
	},

	/**
	 * 弹出微信授权
	 */
	getUserProfile: function(e) {
		wx.getUserProfile({
			desc: '校运通微信授权登录',
			success: (res) => {
				console.log(res.userInfo)
				this.wxLogin(res.userInfo);
			}
		})
	},
	
	wxLogin: function (userInfo){
	  var that = this;
	  wx.login({
	    success: function (res) {
	      console.log(res);
	      if (res.code) {
	        that.userLogin(res.code, userInfo);
	      } else {
	        wx.hideLoading();
	        console.log('登录失败！' + res.errMsg)
	        wx.showToast({
	          title: '登录失败！请重试！',
	          icon: 'none',
	          duration: 2000
	        })
	      }
	    }
	  });
	},
	
	userLogin: function (code, wxUserInfo){
	  var that = this;
	  var postData = {
	    code: code,
	    userInfo: JSON.stringify(wxUserInfo),
	    headUrl: wxUserInfo.avatarUrl,
	    name: wxUserInfo.nickName,
	  };
	
	  util.myRequest(api.WxLogin, postData, function(data){
	    app.globalData.userInfo = data.data;
	    // wx.navigateBack({
	    //   delta: 1
	    // })
	    wx.redirectTo({
	      url: './../userInfo/userInfo'
	    })
	  });
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		if (app.globalData.smsTime > 0) {
			this.countDown();
		}
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {
		return app.globalData.shareInfo;
	},

	// 选择性别男
	chooseMan: function() {
		this.setData({
			man: true
		});
	},

	// 选择性别女
	chooseWoman: function() {
		this.setData({
			man: false
		});
	},

	// 获取姓名
	nameInput: function(e) {
		this.setData({
			name: e.detail.value
		})
	},

	// 微信获取手机号
	getPhoneNumber: function(e) {
		if (app.globalData.userInfo == null) {
			wx.showToast({
				title: '请先微信授权后再试',
				icon: 'none',
				duration: 2000
			});
			return;
		}
		console.log(e.detail.errMsg)
		console.log(e.detail.iv)
		console.log(e.detail.encryptedData)

		var that = this;

		var postData = {};
		postData.token = app.globalData.userInfo.token;
		postData.encryptedData = e.detail.encryptedData;
		postData.iv = e.detail.iv;

		util.myRequest(api.DecodeWxMiniData, postData, function(data) {
			that.setData({
				mobile: data.data.phoneNumber,
				isReadMbile: true,
				isShowAuthCode: false,
			});
		});

	},

	// 获取手机号
	mobileInput: function(e) {
		console.log(e.detail.value);
		if (e.detail.value == '') {
			this.setData({
				mobile: e.detail.value,
				isShowAuthCode: false,
			});
		} else {
			this.setData({
				mobile: e.detail.value,
				isShowAuthCode: true,
			});
		}

	},

	// 获取填写验证码
	codeInput: function(e) {
		this.setData({
			authCode: e.detail.value
		})
	},

	// 倒计时
	countDown: function() {
		var that = this;
		var second = app.globalData.smsTime;
		if (second > 0) {
			this.setData({
				btnCodeText: second
			});
			app.globalData.smsTime = app.globalData.smsTime - 1;
		} else {
			this.setData({
				btnCodeText: '获取验证码'
			})
			return;
		}
		setTimeout(function() {
			that.countDown();
		}, 1000);
	},

	// 获取短信验证码
	getAuthCode: function() {
		if (app.globalData.userInfo == null) {
			wx.showToast({
				title: '请先微信授权后再试',
				icon: 'none',
				duration: 2000
			});
			return;
		}
		console.log('getAuthCode');
		if (app.globalData.smsTime > 0) {
			return;
		}
		var that = this;
		var postData = {};
		postData.token = app.globalData.userInfo.token;
		postData.mobile = this.data.mobile;
		util.myRequest(api.SendSMSCode, postData, function(data) {
			wx.showToast({
				title: '发送成功',
				icon: 'success',
				duration: 2000
			});
			app.globalData.smsTime = 60;
			that.setData({
				isShowAuthCode: true
			});
			that.countDown();
		});
	},

	schoolColumnChange: function(e) {
		if (app.globalData.userInfo == null) {
			wx.showToast({
				title: '请先微信授权后再试',
				icon: 'none',
				duration: 2000
			});
			return;
		}
		var that = this;
		console.log('picker发送选择改变，携带值为', e.detail.value)
		this.setData({
			schoolText: that.data.schoolList[e.detail.value],
			schoolId: that.data.schoolIdList[e.detail.value],
		})
	},

	// 保存并跳转到选择地址
	chooseAddress: function() {

		var that = this;
		var isHaveMobile = this.data.isHaveMobile;
		if (isHaveMobile && !that.data.name) {
			wx.showToast({
				title: '请填写您的称呼',
				icon: 'none',
				duration: 2000
			})
			return;
		}

		if (that.data.mobile == "") {
			wx.showToast({
				title: '请填写手机号',
				icon: 'none',
				duration: 2000
			})
			return;
		}

		if (!util.isPoneAvailable(that.data.mobile)) {
			wx.showToast({
				title: '手机号格式不正确',
				icon: 'none',
				duration: 2000
			})
			return;
		}

		if (isHaveMobile && that.data.schoolText == '请选择') {
			wx.showToast({
				title: '请选择您所在的学校',
				icon: 'none',
				duration: 2000
			})
			return;
		}

		var checkAuthCode = 1;
		//if (that.data.isReadMbile || that.data.effectiveMobile == that.data.mobile){
		if (!that.data.isShowAuthCode) {
			checkAuthCode = 0;
		} else {
			if (that.data.authCode == '') {
				wx.showToast({
					title: '请填写短信验证码',
					icon: 'none',
					duration: 2000
				})
				return;
			}
		}

		// 提交地址
		var postData = {
			token: app.globalData.userInfo.token,
			uName: that.data.name,
			uSex: that.data.man ? 1 : 0,
			uMobile: that.data.mobile,
			uSchool: that.data.schoolText,
			checkAuthCode: checkAuthCode,
			authCode: that.data.authCode,
			uCustomInfo: JSON.stringify({
				csId: that.data.schoolId
			}),
			shareId: app.globalData.shareId,
		};

		util.myRequest(api.SetUserAddition, postData, function(data) {

			util.myRequest(api.IndexNeedInfo + '/' + that.data.schoolId, false, function(data2) {

				app.globalData.hdimg = data2.data.bannerList;

				var userInfo = app.globalData.userInfo;
				userInfo.addition = postData;
				userInfo.addition.uCustomInfo = {
					csId: that.data.schoolId
				};
				app.globalData.userInfo = userInfo;
				
				if (that.data.next == 'back') {
					wx.navigateBack({
						delta: 1
					})
				} else {
					if (app.globalData.userInfo.addition.uName != "") {
						wx.switchTab({
							url: './../home/index',
							success:() => {
								app.wxLogin()
							}
						})
					} else {
						wx.redirectTo({
							url: './../userInfo/userInfo'
						})
					}
				}
			});
		});
	},

	getInfo: function() {

		util.myRequest(api.IndexNeedInfo, false, function(data) {
			app.globalData.hdimg = data.bannerList;
		});
	},

	// 关闭协议
	closePopup: function(e) {
		this.setData({
			isFirst: false
		});
	},

	// 显示协议
	showPopup: function(e) {
		this.setData({
			isFirst: true
		});
	},

	checkboxChange: function(e) {
		console.log('checkbox发生change事件，携带value值为：', e.detail.value)
		if (e.detail.value.length == 0) {
			this.setData({
				isAgree: false
			})
		} else {
			this.setData({
				isAgree: true
			})
		}
	},
})
